package org.bing.engine.health.gather;

import java.io.BufferedReader;
import java.io.IOException;

import org.bing.engine.health.gather.StreamActor.Action;

public class CpuInfoGather extends AbstractGather {
	private static final StreamActor actor = new StreamActor();
	private static final String location = "/proc/stat";
	private long lastIdle = 0, lastTotal = 0;

	@Override
	public Object gather() {
		Object result = actor.doAction(location, new Action() {

			public Object run(BufferedReader reader) throws IOException {
				String line = reader.readLine();
				line = line.substring(4).trim();
				String[] st = line.split(" ");
				long total = 0, idle = Long.parseLong(st[3]);
				for (int i = 0; i < st.length; i++) {
					total += Long.parseLong(st[i]);
				}
				if (lastIdle == 0 && lastTotal == 0) {
					lastIdle = idle;
					lastTotal = total;
					return 0.0;
				}
				long sidle = idle - lastIdle;
				long stotal = total - lastTotal;
				lastIdle = idle;
				lastTotal = total;
				return ((float) ((stotal - sidle) * 10000 / stotal)) / 100;
			}

		});

		return result;
	}

	public static void main(String[] args) throws InterruptedException {
		CpuInfoGather gather = new CpuInfoGather();
		for (int i = 0; i < 10 * 2; i++) {
			System.out.println(gather.gather());
			Thread.sleep(2000);
		}

	}
}
